package com.atguigu.gulimall.product.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: fd
 * @Date 2021/7/13 15:31
 * @Description: Spring Cache 自定义redis缓存配置
 */
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class MyCacheConfig {

//	@Autowired
//	CacheProperties cacheProperties;

	/**
	 * 1.源码配置文件绑定的配置类是这样的
	 * 		@ConfigurationProperties(prefix = "spring.cache")
	 * 		public class CacheProperties {}
	 * @ConfigurationProperties 这个注解只是绑定了配置文件，并没有放在容器里，所以没有效
	 * 2.使注解生效
	 * 		@EnableConfigurationProperties
	 * 		还需要指定绑定哪个类  @EnableConfigurationProperties(CacheProperties.class)
	 *
	 * application.properties 配置文件配置的没有用上
	 * spring.cache.redis.time-to-live=3600000
	 * @author fd
	 * @date 2021/7/13 15:52
	 * @return org.springframework.data.redis.cache.RedisCacheConfiguration
	 */
	@Bean
	RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {

		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

		// config = config.entryTtl();
		// 加入json序列化
		config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.
				fromSerializer(new StringRedisSerializer()));
		config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.
				fromSerializer(new GenericJackson2JsonRedisSerializer()));

		CacheProperties.Redis redisProperties = cacheProperties.getRedis();
		//将配置文件中所有的配置都生效
		if (redisProperties.getTimeToLive() != null) {
			config = config.entryTtl(redisProperties.getTimeToLive());
		}
		if (redisProperties.getKeyPrefix() != null) {
			config = config.prefixKeysWith(redisProperties.getKeyPrefix());
		}
		if (!redisProperties.isCacheNullValues()) {
			config = config.disableCachingNullValues();
		}
		if (!redisProperties.isUseKeyPrefix()) {
			config = config.disableKeyPrefix();
		}

		return config;
	}

}
